import { Form, Input, Select, Button, Modal, Table, Space, Spin, message } from 'antd';
import { ZoomInOutlined, CiOutlined, LoadingOutlined } from '@ant-design/icons';
import { Tag } from 'antd';
// @ts-ignore
import { useModel } from 'umi';
import React, { useState, useEffect } from 'react';
import {
  commitLogSelectList,
  createDeploy,
  deployLog,
  deployLogData,
  diffLog,
  projectSelectList,
  publish,
} from '@/services/project';
import Diff from './diff';
import './index.css';
import type { ColumnsType } from 'antd/es/table';
import GridContentLocal from '@/pages/global/gloadding';
import ConsoleLog from '@/pages/deploy/consolelog';
import app from '@/services/ws/event';
import CodeMirrorShell from '@/pages/global/codeMirrorShell';
// const { TextArea } = Input;
const { Option } = Select;
const App: React.FC = () => {
  const globalData = useModel('globaldata');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOpenDiff, setIsOpenDiff] = useState(false);
  const [loaddingCommit, setLoaddingCommit] = useState(false);
  const [showCode, setShowCode] = useState(false);
  const [showLog, setShowLog] = useState(false);
  const [deployLogDataDetail, setDeployLogDataDetail] = useState<[]>();
  const [deployLogItem, setDeployLogItem] = useState('');
  const [currentParams, setCurrentParams] = useState<{
    deploy_id?: number;
    commit_id?: string;
    project_id?: number;
    page?: number;
    page_size?: number;
  }>({});
  const [diff, setDiff] = useState([]);
  const [buttonDisable, setButtonDisable] = useState(true);
  const [pageData, setPageData] = useState<PRO.PageResponse>({
    list: [],
    page: 0,
    page_size: 0,
    total: 0,
  });
  const [form] = Form.useForm();
  useEffect(() => {
    // @ts-ignore
    app.register('on_refresh', () => {
      getDeployLog();
    });
    return () => {
      //@ts-ignore
      app.forget('on_refresh');
    };
  });
  // useEffect(()=>{
  //   app.register('on_refresh', ()=>{
  //     getDeployLog()
  //   })
  // }, [])

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const getDeployData = async (id: number) => {
    try {
      const data = await deployLogData({
        id: id,
      });
      if (data.log) {
        setShowLog(true);
        setDeployLogDataDetail(JSON.parse(data.log));
      }
    } catch (e) {
      console.log(e);
    }
  };
  const [projectList, setList] = useState([
    {
      project_name: 'ceshi',
      id: 1,
    },
    { project_name: 'ceshi2', id: 2 },
  ]);
  // @ts-ignore
  // @ts-ignore
  const getData = async (
    projectId?: number,
    commitId?: string,
    deployId?: any,
    pageData?: PRO.Page,
  ) => {
    try {
      const params = {
        deploy_id: deployId,
        commit_id: commitId,
        project_id: projectId,
        page: pageData?.page,
        page_size: pageData?.page_size,
      };
      setCurrentParams(params);
      const data = await diffLog(params);
      // @ts-ignore
      setDiff(data);
      setIsOpenDiff(true);
    } catch (e) {}
  };
  const getDeployLog = async (page = 1, pageSize = 10) => {
    try {
      globalData.show();
      const data = await deployLog({
        deploy_comment: '',
        page: page,
        page_size: pageSize,
        status: undefined,
      });
      globalData.hidden();
      setPageData(data);
    } catch (e) {
      globalData.hidden();
      console.error(e);
    }
  };
  const [commitLog, setCommitLog] = useState([]);
  const getSelectData = async () => {
    const data = await projectSelectList();
    setList(data);
  };
  const handleOk = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // @ts-ignore
  const showButton = (record: PRO.DeployLog) => {
    if (record.status == 0) {
      return (
        <Button
          style={{ marginLeft: '10px' }}
          type="primary"
          icon={<CiOutlined />}
          onClick={() => {
            globalData.show();
            publish({ deploy_id: record.id })
              .then(() => {
                globalData.hidden();
                getDeployLog();
              })
              .catch(() => {
                globalData.hidden();
              });
          }}
        >
          发布
        </Button>
      );
    } else {
      return (
        <Button
          style={{ marginLeft: '10px' }}
          type="primary"
          disabled={true}
          icon={<CiOutlined />}
          onClick={() => {
            globalData.show();
            publish({ deploy_id: record.id })
              .then(() => {
                globalData.hidden();
                getDeployLog();
              })
              .catch(() => {
                globalData.hidden();
              });
          }}
        >
          发布
        </Button>
      );
    }
  };

  // @ts-ignore
  // @ts-ignore
  const columns: ColumnsType<PRO.DeployLog> = [
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '发布备注',
      dataIndex: 'deploy_comment',
      key: 'deploy_comment',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        switch (record.status) {
          case 1:
            return (
              <Space>
                <Tag color="#1A73E8">
                  发布中
                  <LoadingOutlined />
                </Tag>
              </Space>
            );
          case 2:
            return (
              <Space>
                <Tag color="#87d068">发布完成:</Tag>
                <Tag color="#87d068">耗时:{record.run_time}s</Tag>
              </Space>
            );
          case 3:
            return (
              <Space>
                <Tag color="#BC5A2B">发布失败:</Tag>
                <Tag color="#BC5A2B">耗时:{record.run_time}s</Tag>
              </Space>
            );
          default:
            return <Tag color="#2db7f5">待发布</Tag>;
        }
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div>
          <Button
            type="dashed"
            icon={<ZoomInOutlined />}
            onClick={() => {
              globalData.show();
              getData(0, '', record.id, {
                page: 1,
                page_size: 30,
              })
                .then(() => {
                  globalData.hidden();
                })
                .catch(() => {
                  globalData.hidden();
                });
            }}
          >
            review
          </Button>
          {showButton(record)}
          <Button
            type="dashed"
            icon={<ZoomInOutlined />}
            onClick={() => {
              globalData.show();
              getDeployData(record.id)
                .then(() => {
                  globalData.hidden();
                })
                .catch(() => {
                  globalData.hidden();
                });
            }}
          >
            log
          </Button>
        </div>
      ),
    },
  ];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const preview = async () => {
    try {
      globalData.show();
      form.validateFields().then(() => {
        const value = form.getFieldsValue();
        getData(value.project_id, value.commit_id, value.deploy_id, {
          page: 1,
          page_size: 30,
        });
        globalData.hidden();
      });
    } catch (e) {
      globalData.hidden();
    }
  };
  useEffect(() => {
    try {
      getSelectData();
      getDeployLog();
    } catch (e) {}
  }, []);
  const handleSubmit = async (data: {
    project_id: number;
    deploy_comment: string;
    commit_id: string;
  }) => {
    try {
      await createDeploy(data);
      setIsModalOpen(false);
      await getDeployLog();
    } catch (e) {
      message.error(e);
    }
  };
  const onFinishFailed = async () => {};
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <GridContentLocal>
      <ConsoleLog />
      <Modal
        open={showLog}
        onOk={() => {
          setShowLog(false);
          setShowCode(false);
        }}
        onCancel={() => {
          setShowLog(false);
          setShowCode(false);
        }}
        title={'选择需要查看的日志'}
      >
        {deployLogDataDetail?.map((item: string) => {
          return (
            <div
              style={{ marginTop: '5px', cursor: 'pointer' }}
              onClick={() => {
                setShowCode(true);
                setDeployLogItem(item);
              }}
            >
              <Tag color="#2db7f5">{item.substring(0, 30) + '...'}</Tag>
            </div>
          );
        })}
      </Modal>
      <CodeMirrorShell
        open={showCode}
        defaultValue={deployLogItem}
        onOk={() => {
          setShowCode(false);
        }}
        onchange={(code: any) => {}}
        okCancel={() => {
          setShowCode(false);
        }}
      />
      <div className="all_loading" style={{ display: 'none' }}>
        <div className="all_loading_inner">
          <Space size="middle">
            <Spin size="large" />
          </Space>
        </div>
      </div>
      <Modal
        title="代码review"
        width={1200}
        open={isOpenDiff}
        onCancel={() => {
          setIsOpenDiff(false);
        }}
        onOk={() => {
          setIsOpenDiff(false);
          setButtonDisable(false);
        }}
      >
        <Diff
          modifyLog={diff}
          pageFun={(page: number, pageSize: number) => {
            const currentData = currentParams;
            currentData['page'] = page;
            currentData['page_size'] = pageSize;
            getData(currentData.project_id, currentData.commit_id, currentData.deploy_id, {
              page: currentData.page,
              page_size: currentData.page_size,
            });
          }}
        />
      </Modal>
      <Button
        type="primary"
        onClick={() => {
          setIsModalOpen(true);
        }}
      >
        新建发布
      </Button>
      <Modal
        width={700}
        title="新建发布"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          style={{ width: 600 }}
          form={form}
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(
              values as { project_id: number; deploy_comment: string; commit_id: string },
            );
          }}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="手动发布"
            name="project_id"
            rules={[
              {
                required: true,
                message: '请输入项目名称!',
              },
            ]}
          >
            <Select
              onChange={async (value: number) => {
                try {
                  setLoaddingCommit(true);
                  setButtonDisable(true);
                  const data = await commitLogSelectList(value);
                  // @ts-ignore
                  setCommitLog(data);
                  setLoaddingCommit(false);
                } catch (e) {
                  setLoaddingCommit(false);
                }
              }}
            >
              {projectList.map((item) => {
                // eslint-disable-next-line react/jsx-key
                return (
                  <Option value={item.id} key={item.id}>
                    {item.project_name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="发布COMMITID"
            name="commit_id"
            rules={[
              {
                required: true,
                message: '请输入提交发布COMMITID!',
              },
            ]}
          >
            <Select
              loading={loaddingCommit}
              onChange={() => {
                setButtonDisable(true);
              }}
            >
              {commitLog.map((item: PRO.Commit) => {
                // eslint-disable-next-line react/jsx-key
                return (
                  <Option value={item.commit_id} key={item.commit_id}>
                    <div className="commit-select">
                      <div>CommitId:{item.commit_id}</div>
                      <div>Date:{item.date}</div>
                      <div>Comment:{item.comment}</div>
                      <div>author:{item.author}</div>
                    </div>
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="发布标题"
            name="deploy_comment"
            rules={[
              {
                required: true,
                message: '请输入发布标题!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Button type="dashed" onClick={preview}>
              代码REVIEW
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: '20px' }}
              disabled={buttonDisable}
            >
              确认发布
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Table
        columns={columns}
        dataSource={pageData.list}
        pagination={{
          showTotal: () => `共 ${pageData?.total} 条`, // 显示总共有多少条
          total: pageData?.total, // 总共有多少条
          onChange: (page, pageSize) => {
            getDeployLog(page, pageSize);
          }, // 页码变化回调函数
          current: pageData.page, // 当前active的页码
          showSizeChanger: true, // 是否显示页面大小变化选择框
        }}
      />
      ;
    </GridContentLocal>
  );
};

// @ts-ignore
export default App;
